package cn.lzx.hrm.userdetail;

import cn.lzx.hrm.domain.LoginUser;
import cn.lzx.hrm.domain.Permission;
import cn.lzx.hrm.mapper.LoginUserMapper;
import cn.lzx.hrm.mapper.PermissionMapper;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Service
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private LoginUserMapper loginUserMapper;

    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<LoginUser> loginUsers = loginUserMapper.selectList(new EntityWrapper<LoginUser>().eq("username", username));

        if (loginUsers==null || loginUsers.size()<1)
            return null;
        System.out.println(loginUsers);
        LoginUser loginUser = loginUsers.get(0);

        //null的权限
        //1 从数据库中查询权限
        List<Permission> permissions = permissionMapper
                .loadPermissionsByUserId(loginUser.getId());

        //2 转换为SPringsecurity所需要权限数据
        List<SimpleGrantedAuthority> authorities = permissions.stream().map(permission -> {
            return new SimpleGrantedAuthority(permission.getSn());
        }).collect(Collectors.toList());

        return new User(loginUser.getUsername(),loginUser.getPassword(),authorities);
    }
}
